<template>
  <div class="add">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        show-icon>
      </el-alert>
      步骤条
      <el-steps
        align-center
        :space="200"
        :active="activeTabs - 0"
        finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tabs标签页 -->
      <el-form label-position="top" :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRef" label-width="100px">
        <el-tabs @tab-click="handleClick" :before-leave="beforeLeave" v-model="activeTabs" tab-position="left">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
            <el-input type="number" v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
            <el-input type="number" v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
            <el-input type="number" v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
              v-model="addGoodsForm.goods_cat"
              :options="cateList"
              :props="cascaderProps"
              @change="cascaderhandleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(item2,index) in item.attr_vals" :key="index" :label="item2" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action: 请求的接口地址，写完整的接口地址，axios对该组件不起作用
            :on-preview：点击预览的回调
            :on-remove：点击移除图片的回调
            list-type: 上传图片后的类型
            -->
            <el-upload
              class="upload-demo"
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              :headers="headersObj"
              :on-success="imgUploadSuccess"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button @click="addGoods" style="margin-top: 10px" type="primary">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog
      title="预览图片"
      :visible.sync="previewDialogVisible"
      width="50%">
      <img style="width: 100%" :src="previewImg" alt=""/>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'loadsh'
export default {
  data () {
    return {
      activeTabs: '0',
      // 添加商品表单
      addGoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        // 商品分类
        goods_cat: [],
        pics: []
      },
      // 验证规则
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 级联选择器所有数据
      cateList: [],
      // 级联选择器双向绑定
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      manyData: [],
      onlyData: [],
      // 上传图片请求头
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      previewDialogVisible: false,
      previewImg: ''
    }
  },

  created () {
    this.getGoodsCate()
  },

  computed: {
    cateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },

  methods: {
    // 获取商品分类
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.cateList = res.data
    },
    cascaderhandleChange () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 只要离开某一标签页即触发
    beforeLeave (activeName, oldActiveName) {
      // activeName: 进入的tab
      // oldActiveName： 离开的tab name
      if (oldActiveName === '0') {
        if (this.addGoodsForm.goods_cat.length !== 3) {
          this.$message.error('请先选择商品分类')
          return false
        }
      }
    },
    // 点击tabs标签页
    async handleClick () {
      // 点击商品参数
      if (this.activeTabs === '1') {
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) return this.$message.error('获取参数失败')
        this.$message.success('获取参数成功')
        this.manyData = res.data
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
      } else if (this.activeTabs === '2') {
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) return this.$message.error('获取属性失败')
        this.$message.success('获取属性成功')
        this.onlyData = res.data
      }
    },
    // 点击预览
    handlePreview (file) {
      this.previewDialogVisible = true
      this.previewImg = file.response.data.url
    },
    // 点击移除
    handleRemove (file) {
      console.log(file)
      var filePath = file.response.data.tmp_path
      var index = this.addGoodsForm.pics.findIndex(item => {
        return filePath === item.pic
      })
      this.addGoodsForm.pics.splice(index, 1)
      console.log(this.addGoodsForm.pics)
    },
    imgUploadSuccess (res) {
      // console.log(res)
      if (res.meta.status === 200) {
        this.addGoodsForm.pics.push({ pic: res.data.tmp_path })
      }
      console.log(this.addGoodsForm)
    },
    addGoods () {
      this.$refs.addGoodsFormRef.validate(async flag => {
        if (!flag) return this.$message.error('亲，请完善基本信息')
        // 实现深拷贝
        // const addGoodsForm = JSON.parse(JSON.stringify(this.addGoodsForm))
        const addGoodsForm = cloneDeep(this.addGoodsForm)
        addGoodsForm.goods_cat = addGoodsForm.goods_cat.join(',')
        // attrs: 用来传递所有动态参数 和静态属性
        addGoodsForm.attrs = []
        // 整理attrs数据
        this.manyData.forEach(item => {
          addGoodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyData.forEach(item => {
          addGoodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        console.log(addGoodsForm.attrs)
        const { data: res } = await this.$axios.post('goods', addGoodsForm)
        if (res.meta.status !== 201) return this.$message.error('创建商品失败')
        this.$message.success('创建商品成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-alert{
  display: flex;
  justify-content: center;
}
.el-steps{
  margin: 15px 0
}
.el-step__title {
  font-size: 12px!important;
}
.el-checkbox {
  margin-right: 0;
}
</style>
